﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xcj.Mes.Core.FileHelper;
using Xcj.Mes.Core.Logger;

namespace Xcj.Mes.Core.Common
{
    public class DeviceParameterHelper
    {
        public static DeviceParameterHelper deviceParameterHelper = new DeviceParameterHelper();
        private static string CurrentDisk = Environment.CurrentDirectory?.Substring(0, 2);

        public string UserName { get; set; } = string.Empty;

        public string UserID { get; set; } = string.Empty;

        public string DeviceSn { get; set; } = string.Empty;

        static DeviceParameterHelper()
        {
            deviceParameterHelper = new DeviceParameterHelper();
        }

        public object lockDeviceParameterItem = new object();
        public Dictionary<string, DeviceParameterItem> dictDeviceParameterItem = new Dictionary<string, DeviceParameterItem>();
        private UInt32 index = 0;

        private DeviceParameterHelper()
        {
            //_ = MyFileHelper.myFileHelper;

            //string fullPath = Assembly.GetExecutingAssembly().Location;
            //string directory = Path.GetDirectoryName(fullPath);
            //string path = $"{directory}\\Config";

            //if (!Directory.Exists(path))
            //    Directory.CreateDirectory(path);

            //string deviceParameterConfigFile = $"{path}\\设备参数信息.xlsx";

            //lock (lockDeviceParameterItem)
            //{
            //    try
            //    {
            //        dictDeviceParameterItem.Clear();
            //        InitDeviceParameterItem(deviceParameterConfigFile);
            //    }
            //    catch (Exception ex) { MyLogger.Log(ref ex); }
            //}
        }

        private void InitDeviceParameterItem(string filePath)
        {
            //IWorkbook workbook;

            //FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            //// 根据文件扩展名判断是.xls还是.xlsx
            //if (filePath.IndexOf(".xlsx") > 0)
            //{
            //    workbook = new XSSFWorkbook(file);
            //}
            //else if (filePath.IndexOf(".xls") > 0)
            //{
            //    workbook = new HSSFWorkbook(file);
            //}
            //else
            //{
            //    throw new Exception("不支持的文件格式");
            //}

            //// 获取第一个工作表
            //ISheet sheet = workbook.GetSheetAt(0);

            //uint id = 0;

            //// 遍历工作表中的所有行和列
            //for (int i = sheet.FirstRowNum + 2; i <= sheet.LastRowNum; i++)
            //{
            //    IRow row = sheet.GetRow(i);
            //    if (row == null)
            //        continue;       // 如果行为空，跳过

            //    DeviceParameterItem deviceParameterItem = new DeviceParameterItem();

            //    deviceParameterItem.Index = id++;

            //    for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
            //    {
            //        ICell cell = row.GetCell(j);
            //        if (cell == null)
            //            continue;   // 如果单元格为空，跳过

            //        string value = string.Empty;

            //        // 根据单元格类型获取值
            //        switch (cell.CellType)
            //        {
            //            case CellType.String:
            //                value = cell.StringCellValue;
            //                break;

            //            case CellType.Numeric:
            //                if (DateUtil.IsCellDateFormatted(cell))
            //                {
            //                    value = cell.DateCellValue?.ToString("yyyy年MM月dd日 HH:mm:ss");
            //                }
            //                else
            //                {
            //                    //long ticks = (long)(cell.NumericCellValue * 1000);  // 将double值转换为毫秒
            //                    //DateTime dateTimeValue = new DateTime(ticks);       // 将毫秒值转换为DateTime类型
            //                    //value = dateTimeValue.ToString("yyyy年MM月dd日 HH:mm:ss");
            //                    value = cell.NumericCellValue.ToString();
            //                }
            //                break;

            //            case CellType.Boolean:
            //                value = cell.BooleanCellValue ? "true" : "false";
            //                break;

            //            default:
            //                Console.Write("未知类型\t");
            //                break;
            //        }

            //        switch (j)
            //        {
            //            case 0:     // 参数地址
            //                deviceParameterItem.ParameterAddress = value?.Trim();
            //                break;

            //            case 1:     // 参数名称
            //                deviceParameterItem.ParameterText = value?.Trim();
            //                break;

            //            default:
            //                break;
            //        }
            //    }

            //    if ((!string.IsNullOrEmpty(deviceParameterItem.ParameterAddress))
            //        && (!string.IsNullOrEmpty(deviceParameterItem.ParameterText)))
            //    {
            //        if (dictDeviceParameterItem.ContainsKey(deviceParameterItem.ParameterAddress))
            //            dictDeviceParameterItem.Remove(deviceParameterItem.ParameterAddress);
            //        dictDeviceParameterItem.Add(deviceParameterItem.ParameterAddress, deviceParameterItem);
            //    }
            //}

            //try
            //{
            //    // 关闭工作簿和文件流
            //    workbook.Close();
            //}
            //catch { }

            //try
            //{
            //    file.Close();
            //}
            //catch { }
        }

        public void UpdateDeviceParameterItem(string parameterAddress, string oldValue, string newValue)
        {
            if ((string.IsNullOrEmpty(parameterAddress))
                //|| (string.IsNullOrEmpty(UserName) && string.IsNullOrEmpty(UserID))
                || (oldValue == newValue))
                return;

            lock (lockDeviceParameterItem)
            {
                if (!dictDeviceParameterItem.ContainsKey(parameterAddress))
                    return;

                DeviceParameterItem deviceParameterItem = dictDeviceParameterItem[parameterAddress];

                deviceParameterItem.DeviceSn = DeviceSn;
                deviceParameterItem.OldValue = oldValue;
                deviceParameterItem.NewValue = newValue;
                deviceParameterItem.UserName = UserName;
                deviceParameterItem.UserID   = UserID;
                deviceParameterItem.Timestamp = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");

                DateTime now = DateTime.Now;

                string path = $"{CurrentDisk}\\电芯数据\\日志\\参数修改日志\\{now:yyyy年MM月}";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                string saveFileName = $"{path}\\{now:yyyy年MM月dd日}.csv";
                if (!File.Exists(saveFileName))
                {
                    MyFileHelper.myFileHelper.CreateFile(saveFileName, true, Encoding.UTF8);
                    MyFileHelper.myFileHelper.Append(saveFileName, "序号,设备名称,设备编号,参数地址,参数名称,原值,新值,员工姓名,员工工号,修改时间", Encoding.UTF8);
                    index = 0;
                }

                try
                {
                    if (index <= 0)
                        index = GetLineCount(saveFileName);

                    MyFileHelper.myFileHelper.Append(saveFileName, $"\r\n{index},{deviceParameterItem.DeviceName},{deviceParameterItem.DeviceSn},{deviceParameterItem.ParameterAddress},{deviceParameterItem.ParameterText},{deviceParameterItem.OldValue},{deviceParameterItem.NewValue},{deviceParameterItem.UserName},{deviceParameterItem.UserID},{deviceParameterItem.Timestamp:yyyy年MM月dd日 HH:mm:ss}", Encoding.UTF8);

                    index++;
                }
                catch (Exception ex) { MyLogger.Log(ex); }
            }
        }

        private UInt32 GetLineCount(string filePath)
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                UInt32 count = 0;
                while (!sr.EndOfStream)
                {
                    sr.ReadLine();
                    count++;
                }
                return count;
            }
        }
    }

    public class DeviceParameterItem
    {
        public UInt32 Index { get; set; } = 0;                              // 序号

        public string DeviceName { get; set; } = "卷绕机";                  // 设备名称

        public string DeviceSn { get; set; } = string.Empty;                // 设备编码

        public string ParameterAddress { get; set; } = string.Empty;        // 设备参数地址

        public string ParameterText { get; set; } = string.Empty;           // 参数内容

        public string OldValue { get; set; } = string.Empty;                // 原值

        public string NewValue { get; set; } = string.Empty;                // 新值

        public string UserName { get; set; } = string.Empty;                // 操作员姓名

        public string UserID { get; set; } = string.Empty;                  // 操作员工号

        public string Timestamp { get; set; } = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");   // 修改时间
    }
}
